package org.example.myleet.p791;

import java.util.Arrays;

public class Solution {
    public String customSortString(String order, String s) {
        int[] charCounts = new int[128];
        for (int i = 0; i < s.length(); ++i) {
            ++charCounts[s.charAt(i)];
        }
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < order.length(); ++i) {
            char ch = order.charAt(i);
            int charCount = charCounts[ch];
            for (int j = 0; j < charCount; ++j) {
                result.append(ch);
            }
            charCounts[ch] = 0;
        }
        for (int i = 0; i < charCounts.length; ++i) {
            int charCount = charCounts[i];
            for (int j = 0; j < charCount; ++j) {
                result.append((char) i);
            }
        }
        return result.toString();
    }

//    public String customSortString(String order, String s) {
//        int[] orderMap = new int[128];
//        Arrays.fill(orderMap, Integer.MAX_VALUE);
//        for (int i = 0; i < order.length(); ++i) {
//            char ch = order.charAt(i);
//            orderMap[ch] = i;
//        }
//        char[] chars = s.toCharArray();
//        Character[] characters = new Character[chars.length];
//        for (int i = 0; i < chars.length; ++i) {
//            characters[i] = chars[i];
//        }
//        Arrays.sort(characters, (ch1, ch2) -> {
//            int ch1o = orderMap[ch1];
//            int ch2o = orderMap[ch2];
//            if (ch1o == ch2o) {
//                return ch1 - ch2;
//            }
//            return ch1o - ch2o;
//        });
//        StringBuilder result = new StringBuilder();
//        for (Character character : characters) {
//            result.append(character);
//        }
//        return result.toString();
//    }
}
